package com.whut.transportation;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.Toast;

import com.whut.transportation.entity.GuDao;
import com.whut.transportation.entity.Message;
import com.whut.transportation.entity.TaskInfo;
import com.whut.transportation.entity.TrainCheckInfo;
import com.whut.transportation.entity.TransInfo;
import com.whut.transportation.network.HttpManager;
import com.whut.transportation.network.HttpRequestVo;
import com.whut.transportation.network.WebServiceRequestVo;
import com.whut.transportation.parser.JSONParser;
import com.whut.transportation.ui.BaseActivity;
import com.whut.transportation.utils.Constant;
import com.whut.transportation.utils.FormFile;

public class UploadPhoneActivity extends BaseActivity {
	
	private TransInfo transinfo;
	//private TrainCheckInfo trainCheckInfo;
	private String checkResult;
	private SharedPreferences preferences;//偏好
	
	private GridView gridView1;              //网格显示缩略图
	private Button phone_submit;             //发布按钮
	private final int IMAGE_OPEN = 1;        //打开图片标记
	private String pathImage;                //选择图片路径
	private Bitmap bmp;                      //导入临时图片
	private ArrayList<HashMap<String, Object>> imageItem;
	private List<String> pathImageList;//获取所有图片的路径
	private SimpleAdapter simpleAdapter;     //适配器
	
	private int gudaoId;
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.phone_submit:
			try {
				submitPhone();
			} catch (IOException e) {
				e.printStackTrace();
			}
			break;
		default:
			break;
		}
		super.onClick(v);
	}
	private void submitPhone() throws IOException {
		if(pathImageList.size()>0){
			WebServiceRequestVo vo =new WebServiceRequestVo();
			vo.requestUrl = Constant.UPLOAD_PHONE;
			vo.context = mContext;
			FormFile[] formFiles = new FormFile[pathImageList.size()];
			for(int i=0;i<formFiles.length;i++){
				File uploadFile = saveFile(getimage(pathImageList.get(i)),Environment.getExternalStorageDirectory().getPath()+"/temy","tem_"+i+".jpg");
				FormFile formFile = new FormFile(uploadFile, "myFile", "image/pjpeg");
				formFiles[i] = formFile;
			}
			vo.formFile = formFiles;
			HashMap<String, String> req = new HashMap<String, String>();
			req.put("id", transinfo.getId());
			req.put("type", String.valueOf(transinfo.getType()));
			req.put("jiancha.shunhao", transinfo.getNumber());
			req.put("trainnumber", transinfo.getTrainNumber());
			req.put("checkResult", checkResult);	
			if(transinfo.getFlag()==0){
				req.put("flag", String.valueOf(0));
			} else {
				req.put("flag", String.valueOf(2));
			}
			vo.requestDataMap = req;
			vo.parser = new JSONParser(Message.class);
			getDataFromWebService(vo, new DataCallback<HashMap<String, Object>>() {
				@Override
				public void onStart() {
					showProgressDialog(getResources().getString(R.string.loading_content));
				}
				@Override
				public void onFailed() {
					showNetErrorDialog();
				}
				@Override
				public void processData(HashMap<String, Object> paramObject,boolean paramBoolean) {
					Message message = (Message) paramObject.get("result");
					if(message.getMessage()==1){
						if(Integer.parseInt(checkResult)==2){
							Toast.makeText(mContext, "车辆出现问题，无法维修，等待处理", Toast.LENGTH_SHORT).show();
							Intent entruckIntent = new Intent(UploadPhoneActivity.this, HomeActivity.class);
							startActivity(entruckIntent);
						} else {
							if(transinfo.getFlag() == 0){
								if(transinfo.getType()==0){
									Intent entruckIntent = new Intent(UploadPhoneActivity.this,TransInfoActivity.class);
									entruckIntent.putExtra("gudao",new GuDao(transinfo.getGudao(), 0));
									startActivity(entruckIntent);
								} else {
									Intent entruckIntent = new Intent(UploadPhoneActivity.this,TransInfoSckActivity.class);
									entruckIntent.putExtra("gudao",new GuDao(transinfo.getGudao(), 0));
									startActivity(entruckIntent);
								}
							} else if(transinfo.getFlag()==2){
								Toast.makeText(mContext, "处理结束", Toast.LENGTH_SHORT).show();
								Intent entruckIntent = new Intent(UploadPhoneActivity.this, HomeActivity.class);
								startActivity(entruckIntent);
							}
							finish();
						}
					} else {
						Toast.makeText(mContext, "提交失败", Toast.LENGTH_SHORT).show();
					}
				}
				@Override
				public void onFinish() {
					closeProgressDialog();
				}
			});
		} else {
			updateTransportation();
		}
	}
	/**
	 * 更新项目状态
	 * 方法目前没用
	 */
	private void updateTransportation() {
		HttpRequestVo vo = new HttpRequestVo();
		vo.requestUrl = Constant.UPDATE_JIANCHA_SECOND_INFO;
		vo.context = mContext;
		vo.parser = new JSONParser(Message.class);
		HashMap<String, String> req = new HashMap<String, String>();
		req.put("jiancha.shunhao", transinfo.getNumber());
		req.put("type", String.valueOf(transinfo.getType()));
		req.put("checkResult", checkResult);
		if(transinfo.getFlag()==0){
			req.put("flag", String.valueOf(0));
		} else {
			req.put("flag", String.valueOf(2));
		}
		vo.requestDataMap = req;
		getDataFromServer(HttpManager.POST_MOTHOD, vo, new DataCallback<HashMap<String, Object>>() {
					@Override
					public void onStart() {
					}
					@Override
					public void onFailed() {
						showNetErrorDialog();
					}
					@Override
					public void processData(HashMap<String, Object> paramObject,boolean paramBoolean) {
						Message message = (Message) paramObject.get("result");
						if(message.getMessage()==1){
							if(Integer.parseInt(checkResult)==2){
								Toast.makeText(mContext, "车辆出现问题，无法维修，等待处理", Toast.LENGTH_SHORT).show();
								Intent entruckIntent = new Intent(UploadPhoneActivity.this, HomeActivity.class);
								startActivity(entruckIntent);
							} else {
								if(transinfo.getFlag() == 0){
									if(transinfo.getType()==0){
										Intent entruckIntent = new Intent(UploadPhoneActivity.this,EntruckDetailActivity.class);
										entruckIntent.putExtra("transinfo",transinfo);
										startActivity(entruckIntent);
									} else {
										Intent entruckIntent = new Intent(UploadPhoneActivity.this,UnloadDetailActivity.class);
										entruckIntent.putExtra("transinfo",transinfo);
										startActivity(entruckIntent);
									}
								} else if(transinfo.getFlag()==2){
									Toast.makeText(mContext, "处理结束", Toast.LENGTH_SHORT).show();
									Intent entruckIntent = new Intent(UploadPhoneActivity.this, HomeActivity.class);
									startActivity(entruckIntent);
								}
							}
						} else {
							Toast.makeText(mContext, "提交失败", Toast.LENGTH_SHORT).show();
						}
					}
					@Override
					public void onFinish() {
						closeProgressDialog();
					}
				});
	}

	@Override
	protected void onResume() {
		super.onResume();
		if(!TextUtils.isEmpty(pathImage)){
			pathImageList.add(pathImage);
			Bitmap addbmp=BitmapFactory.decodeFile(pathImage);
			HashMap<String, Object> map = new HashMap<String, Object>();
	        map.put("itemImage", addbmp);
	        imageItem.add(map);
	        simpleAdapter = new SimpleAdapter(this, 
	        		imageItem, R.layout.griditem_addpic, 
	                new String[] { "itemImage"}, new int[] { R.id.imageView1}); 
	        simpleAdapter.setViewBinder(new ViewBinder() {  
			    @Override  
			    public boolean setViewValue(View view, Object data, String textRepresentation) {  
			        if(view instanceof ImageView && data instanceof Bitmap){  
			            ImageView i = (ImageView)view;  
			            i.setImageBitmap((Bitmap) data);  
			            return true;  
			        }  
			        return false;  
			    }
	        }); 
	        gridView1.setAdapter(simpleAdapter);
	        simpleAdapter.notifyDataSetChanged();
			//刷新后释放防止手机休眠后自动添加
	        pathImage = null;
		}
	}

	@Override
	protected void loadViewLayout() {
		setContentView(R.layout.activity_upload_phone);
		Intent intent = getIntent();
		transinfo = (TransInfo)intent.getSerializableExtra("transinfo");
		checkResult = intent.getStringExtra("checkResult");
		gudaoId=intent.getIntExtra("gudaoid", 0);
		preferences = getSharedPreferences("userId", Context.MODE_PRIVATE);
		setTitleBarView(true, "上传照片", -1, true);
		/*
         * 防止键盘挡住输入框
         * 不希望遮挡设置activity属性 android:windowSoftInputMode="adjustPan"
         * 希望动态调整高度 android:windowSoftInputMode="adjustResize"
         */
        getWindow().setSoftInputMode(WindowManager.LayoutParams.
        		SOFT_INPUT_ADJUST_PAN);
        //锁定屏幕
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	}
	@Override
	protected void findViewById() {
		gridView1 = (GridView) findViewById(R.id.gridView1);
		phone_submit = (Button) findViewById(R.id.phone_submit);
	}

	@Override
	protected void afterFindViewId() {
		 /*
         * 载入默认图片添加图片加号
         * 通过适配器实现
         * SimpleAdapter参数imageItem为数据源 R.layout.griditem_addpic为布局
         */
		pathImageList = new ArrayList<String>();
		
        bmp = BitmapFactory.decodeResource(getResources(), R.drawable.gridview_addpic); //加号
        imageItem = new ArrayList<HashMap<String, Object>>();
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("itemImage", bmp);
        imageItem.add(map);
        simpleAdapter = new SimpleAdapter(this, 
        		imageItem, R.layout.griditem_addpic, 
                new String[] { "itemImage"}, new int[] { R.id.imageView1}); 
        /*
         * HashMap载入bmp图片在GridView中不显示,但是如果载入资源ID能显示 如
         * map.put("itemImage", R.drawable.img);
         * 解决方法:
         *              1.自定义继承BaseAdapter实现
         *              2.ViewBinder()接口实现
         */
        simpleAdapter.setViewBinder(new ViewBinder() {  
		    @Override  
		    public boolean setViewValue(View view, Object data,  
		            String textRepresentation) {  
		        // TODO Auto-generated method stub  
		        if(view instanceof ImageView && data instanceof Bitmap){  
		            ImageView i = (ImageView)view;  
		            i.setImageBitmap((Bitmap) data);  
		            return true;  
		        }  
		        return false;  
		    }
        });  
        gridView1.setAdapter(simpleAdapter);
        
        /*
         * 监听GridView点击事件
         * 报错:该函数必须抽象方法 故需要手动导入import android.view.View;
         */
        gridView1.setOnItemClickListener(new OnItemClickListener() {
  			@Override
			public void onItemClick(AdapterView<?> parent, View v, int position, long id)
			{
  				if( imageItem.size() == 10) { //第一张为默认图片
  					Toast.makeText(UploadPhoneActivity.this, "图片数9张已满", Toast.LENGTH_SHORT).show();
  				}
  				else if(position == 0) { //点击图片位置为+ 0对应0张图片
  					Toast.makeText(UploadPhoneActivity.this, "添加图片", Toast.LENGTH_SHORT).show();
  					//选择图片
  					Intent intent = new Intent(Intent.ACTION_PICK,       
  	                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);  
  	                startActivityForResult(intent, IMAGE_OPEN);  
  	                //通过onResume()刷新数据
  				}
  				else {
  					dialog(position);
  					//Toast.makeText(MainActivity.this, "点击第" + (position + 1) + " 号图片", 
  					//		Toast.LENGTH_SHORT).show();
  				}
				
			}
  		});
	}

	//获取图片路径 响应startActivityForResult  
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        super.onActivityResult(requestCode, resultCode, data);        
        //打开图片  
        if(resultCode==RESULT_OK && requestCode==IMAGE_OPEN) {        
            Uri uri = data.getData();  
            if (!TextUtils.isEmpty(uri.getAuthority())) {  
                //查询选择图片  
                Cursor cursor = getContentResolver().query(  
                        uri,  
                        new String[] { MediaStore.Images.Media.DATA },  
                        null,   
                        null,   
                        null);  
                //返回 没找到选择图片  
                if (null == cursor) {  
                    return;  
                }  
                //光标移动至开头 获取图片路径  
                cursor.moveToFirst();  
                pathImage = cursor.getString(cursor  
                        .getColumnIndex(MediaStore.Images.Media.DATA));  
            }
        }  //end if 打开图片
    }
	
	@Override
	protected void processLogic() {
		
	}

	@Override
	protected void setListener() {
		phone_submit.setOnClickListener(this);
	}

	@Override
	protected void getDataAgain() {
		
	}
	
	
	/*
     * Dialog对话框提示用户删除操作
     * position为删除图片位置
     */
    protected void dialog(final int position) {
    	AlertDialog.Builder builder = new Builder(UploadPhoneActivity.this);
    	builder.setMessage("确认移除已添加图片吗？");
    	builder.setTitle("提示");
    	builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
    		@Override
    		public void onClick(DialogInterface dialog, int which) {
    			dialog.dismiss();
    			imageItem.remove(position);
    			pathImageList.remove(position-1);
    	        simpleAdapter.notifyDataSetChanged();
    		}
    	});
    	builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
    		@Override
    		public void onClick(DialogInterface dialog, int which) {
    			dialog.dismiss();
    			}
    		});
    	builder.create().show();
    }
    
    private Bitmap compressImage(Bitmap image) {  
    	  
        ByteArrayOutputStream baos = new ByteArrayOutputStream();  
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中  
        int options = 100;  
        while ( baos.toByteArray().length / 1024>100) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩         
            baos.reset();//重置baos即清空baos  
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中  
            options -= 10;//每次都减少10  
        }  
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中  
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片  
        return bitmap;  
    } 
    
    private Bitmap getimage(String srcPath) {  
        BitmapFactory.Options newOpts = new BitmapFactory.Options();  
        //开始读入图片，此时把options.inJustDecodeBounds 设回true了  
        newOpts.inJustDecodeBounds = true;  
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath,newOpts);//此时返回bm为空  
          
        newOpts.inJustDecodeBounds = false;  
        int w = newOpts.outWidth;  
        int h = newOpts.outHeight;  
        //现在主流手机比较多是800*480分辨率，所以高和宽我们设置为  
        float hh = 800f;//这里设置高度为800f  
        float ww = 480f;//这里设置宽度为480f  
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可  
        int be = 1;//be=1表示不缩放  
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放  
            be = (int) (newOpts.outWidth / ww);  
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放  
            be = (int) (newOpts.outHeight / hh);  
        }  
        if (be <= 0)  
            be = 1;  
        newOpts.inSampleSize = be;//设置缩放比例  
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了  
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);  
        return compressImage(bitmap);//压缩好比例大小后再进行质量压缩  
    }
    
    /**  
    * 将Bitmap转换成文件
     * 保存文件  
     * @param bm  
     * @param fileName  
     * @throws IOException
     */
    public File saveFile(Bitmap bm,String path, String fileName) throws IOException {   
        File dirFile = new File(path);    
        if(!dirFile.exists()){    
            dirFile.mkdir();
        }
        File myCaptureFile = new File(path , fileName);    
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));    
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);    
        bos.flush();
        bos.close();    
        return myCaptureFile;
    }
    
    /**
     * 删除文件夹以及目录下的文件
     * @param   filePath 被删除目录的文件路径
     * @return  目录删除成功返回true，否则返回false
     */
    public boolean deleteDirectory(String filePath) {
    boolean flag = false;
        //如果filePath不以文件分隔符结尾，自动添加文件分隔符
        if (!filePath.endsWith(File.separator)) {
            filePath = filePath + File.separator;
        }
        File dirFile = new File(filePath);
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        flag = true;
        File[] files = dirFile.listFiles();
        //遍历删除文件夹下的所有文件(包括子目录)
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile()) {
            //删除子文件
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag) break;
            } else {
            //删除子目录
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag) break;
            }
        }
        if (!flag) return false;
        //删除当前空目录
        return dirFile.delete();
    }
    
	
}
